package com.authine.cloudpivot.ext.controller.workList;


import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSONObject;
import com.authine.cloudpivot.engine.api.model.organization.UserModel;
import com.authine.cloudpivot.engine.api.model.runtime.BizObjectCreatedModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkItemModel;
import com.authine.cloudpivot.engine.api.model.runtime.WorkflowInstanceModel;
import com.authine.cloudpivot.engine.enums.status.SequenceStatus;
import com.authine.cloudpivot.ext.Utils.CustomSchemaCode;
import com.authine.cloudpivot.ext.Utils.Utils;
import com.authine.cloudpivot.ext.service.CloudSqlService;
import com.authine.cloudpivot.web.api.controller.base.BaseController;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.Optional;

@Slf4j
@RestController
@RequestMapping("/public/BusinessTripPlanController")
public class BusinessTripPlanController extends BaseController {



    @Autowired
    CloudSqlService sqlService;

    @RequestMapping("finish")
    public void finish(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.BusinessTripPlan, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.BusinessTripPlanDetail);
        String approval = getFileBaseInfoWorkFlowApproval(bizObject,"Activity7");
        for (Map<String, Object> map : list) {
            try {
                Map<String, Object> data = Utils.fileInfoBaseMap(map,approval);
                // 判断是否是修改
                String basicId = MapUtils.getString(map, "basicId", "");
                if(StringUtils.isNotBlank(basicId)){
                    //基础信息表id
                    data.put("id",basicId);
                }
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.BusinessTripPlanBasic, data, false);
                model.setSequenceStatus(SequenceStatus.COMPLETED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                finishOrModifiyProcess(data);
            } catch (Exception e) {
                log.info("原始表数据:{}", JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }
    private void finishOrModifiyProcess(Map<String,Object> map) {
        if (map == null) {
            log.info("数据为空，写入存储过程失败");
            return;
        }
        Map<String,Object> company = ( Map<String,Object>)map.get("company");
        String companyNumber = company.get("id").toString();
        String eventCode = MapUtils.getString(map, "eventCode", "");
        String item = MapUtils.getString(map, "item", "");
        String responsibleDeptFNumber = MapUtils.getString(map, "responsibleDeptFNumber", "");
        String responsiblePersonNumber = MapUtils.getString(map, "responsiblePersonNumber", "");
        String region = MapUtils.getString(map, "region", "");
        String arrivalDate = MapUtils.getString(map, "arrivalDate", "");
        String workDesc = MapUtils.getString(map, "workDesc", "");
        String approval = MapUtils.getString(map, "approval", ""); // 审批人
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].SyncBusinessPlan '%s','%s','%s','%s','%s','%s','%s','%s','%s'",
                companyNumber,eventCode,item,responsibleDeptFNumber,responsiblePersonNumber,region,arrivalDate,workDesc,approval);
        log.info("\n==========准备调用[出差计划]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[出差计划]存储过程执行完成");
    }



    @RequestMapping("toVoid")
    public void toVoid(String bizId) {
        BizObjectCreatedModel bizObject = getBizObjectFacade().getBizObject(CustomSchemaCode.BusinessTripPlanCancel, bizId);
        List<Map<String, Object>> list = (List<Map<String, Object>>) bizObject.get(CustomSchemaCode.BusinessTripPlanDetailCancel);
        //获取审批人
        String approval = getFileBaseInfoWorkFlowApproval(bizObject,"Activity7");
        for (Map<String, Object> map : list) {
            try {
                String bascid = existsBizObject(map);
                //判断是否已存在，如果不存在，放弃这条数据，直接跳过此次循环
                if (StringUtils.isBlank(bascid)) {
                    continue;
                }
                //获取数据
                Map<String, Object> data = Utils.fileInfoBaseMap(map,approval);
                data.put("id",bascid);
                BizObjectCreatedModel model = new BizObjectCreatedModel(CustomSchemaCode.BusinessTripPlanBasic, data, false);
                model.setSequenceStatus(SequenceStatus.CANCELED.name());
                getBizObjectFacade().saveBizObject(CustomSchemaCode.adminUserId, model, false);
                //调用存储过程
                Map<String, Object> company = ( Map<String, Object> )map.get("company");
                toVoidProcess(company.get("id").toString(),MapUtils.getString(map, "eventCode", ""));
            } catch (Exception e) {
                log.info("参数：{}",JSONObject.toJSONString(map));
                e.printStackTrace();
            }
        }
    }

    /**
     * 命名记录作废存储过程
     */
    private void toVoidProcess(String companyNumber,String eventCode) {
        String execSql = String.format("exec [HG_LINK].[hg].[dbo].BusPlanVoid '%s','%s'",
                companyNumber,eventCode);
        log.info("\n==========准备调用[出差计划作废]存储过程:{}", execSql);
        sqlService.execute(CloudSqlService.htEas, execSql);
        log.info("\n=============[出差计划作废]存储过程执行完成");
    }

    /**
     * 查询审批人,返回  员工号+姓名
     *
     * @param bizObject
     * @return
     */
    private String getFileBaseInfoWorkFlowApproval(BizObjectCreatedModel bizObject,String finalActivityCode) {
        WorkflowInstanceModel instanceModel = getWorkflowInstanceFacade().getByObjectId(bizObject.getId());
        List<WorkItemModel> workItems = getWorkflowInstanceFacade().getWorkItems(instanceModel.getId(), true);
        Optional<WorkItemModel> first = workItems.stream().filter(a -> a.getActivityCode().equals(finalActivityCode)).findFirst();
        String participant = null;
        if (first.isPresent()) {
            WorkItemModel workItemModel = first.get();
            participant = workItemModel.getParticipant();
        }
        if (participant == null) {
            participant = bizObject.getCreater().getId();
        }
        UserModel user = getOrganizationFacade().getUser(participant);
        return new StringBuilder(user.getEmployeeNo()).append("　").append(user.getName()).toString();
    }

    /**
     * 判断是否已存在
     *
     * @return
     */
    private String existsBizObject(Map data) {
        //事项基础表id
        String eventObjectId = (String) data.get("eventObjectId");
        String tableName = getBizObjectFacade().getTableName(CustomSchemaCode.BusinessTripPlanBasic);
        StringBuilder sql = new StringBuilder("select id  from ").append(tableName).append(" where id ='").append(eventObjectId).append("'");
        Map<String, Object> map = sqlService.getMap(sql.toString());
        return (String) map.get("id");
    }
}
